package wifiunion.com.notice.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aspsine.irecyclerview.IRecyclerView;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import wifiunion.com.notice.BaseFragment;
import wifiunion.com.notice.BasePresenter;
import wifiunion.com.notice.Constants;
import wifiunion.com.notice.MyNoticeListener;
import wifiunion.com.notice.NoticeContact;
import wifiunion.com.notice.R;
import wifiunion.com.notice.adapter.NoticeMainAdapter;
import wifiunion.com.notice.adapter.RelevanceNoticeMainAdapter;
import wifiunion.com.notice.entity.NoticeInfoList;
import wifiunion.com.notice.presenter.AddRelevanceNoticePresenter;
import wifiunion.com.notice.presenter.RelevanceNoticeListPresenter;
import wifiunion.com.notice.utils.ClickTimeSpanUtil;
import wifiunion.com.notice.utils.SharedPreferencesUtils;
import wifiunion.com.notice.widget.LoadMoreFooterView;
import wifiunion.com.notice.widget.TipsDialog;
import wifiunion.com.notice.widget.selectmemberdialog.SelectMemberDialog;

/**
 *
 * 关联通知
 */

public class AddRelevanceNoticeFragment extends BaseFragment implements NoticeContact.RelevanceNoticeListView, View.OnClickListener,NoticeContact.AddRelevanceNoticeView {

    private View mMainView;

    private LoadMoreFooterView mLoadMoreFooterView;
    private IRecyclerView mRecyclerView;
    private EditText searchEt;

    private RelevanceNoticeMainAdapter mAdapter;

    //分组成员
    private TextView addSBDXTv;


    private RelevanceNoticeListPresenter mRelevanceNoticeListPresenter;
    private ArrayList<NoticeInfoList> noticeUserList = new ArrayList<NoticeInfoList>();

    private LinearLayout mGroupLayout, mListHeaderLayout;

    //当前通知的UUid
    private String noticeUuid;

    private int mType = 1;

//    private AddNoticeUserDialog mAddNoticeUserDialog;

    private SelectMemberDialog selectMemberDialog;

    private TextView headDowntv;
    private TextView headUpTv;
    private int pageType;

    private ImageView ovalsbdxIv;
    private TextView titlesbdxTv;

    private TextView groupDelTv;

    private Button searchBtn;

    private LinearLayout filterLayout2;

    private NoticeInfoList mNoticeInfoList;

    private RelativeLayout guideRl;

    private RelativeLayout dataRl;

    private RelativeLayout bottonRl;

    private AddRelevanceNoticePresenter mAddRelevanceNoticePresenter;




    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mMainView = inflater.inflate(R.layout.fragment_addrelevancenoticefragment, container, false);
        mRelevanceNoticeListPresenter = new RelevanceNoticeListPresenter(getContext(), this);
        mAddRelevanceNoticePresenter = new AddRelevanceNoticePresenter(getContext(), this);
        Bundle bundle = getArguments();
        if (null != bundle) {
            pageType = bundle.getInt("pageType");
            if (pageType == 0) {
                mNoticeInfoList = (NoticeInfoList) bundle.getSerializable("notice");
                noticeUuid = mNoticeInfoList.getUuid();


            }
        }

        initview();

        return mMainView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();

    }

    @Override
    public void onResume() {
        super.onResume();
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                    getFragmentManager().popBackStack();
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    public void initview() {

        ovalsbdxIv = (ImageView) mMainView.findViewById(R.id.oval_gltz_iv);
        ovalsbdxIv.setBackgroundResource(R.drawable.notice_mark_material_select);

//        guideRl = (RelativeLayout) mMainView.findViewById(R.id.notice_guide_rl);
        dataRl = (RelativeLayout) mMainView.findViewById(R.id.notice_data_rl);

        if (pageType == 0) {
//            boolean isguide = SharedPreferencesUtils.getBooleanSharedPreferences(
//                    "noticeguide", getActivity());
//            if (!isguide) {
//                guideRl.setVisibility(View.VISIBLE);
//                dataRl.setVisibility(View.GONE);
//            } else {
//                guideRl.setVisibility(View.GONE);
                dataRl.setVisibility(View.VISIBLE);
//            }
        }


//        bottonRl = (RelativeLayout) mMainView.findViewById(R.id.botton_rl);
//        bottonRl.setOnClickListener(this);

        mListHeaderLayout = (LinearLayout) mMainView.findViewById(R.id.list_noticelistheader);
        mRecyclerView = (IRecyclerView) mMainView.findViewById(R.id.notice_irecyclerView);
        addSBDXTv = (TextView) mMainView.findViewById(R.id.group_add_tv);
        addSBDXTv.setText("添加关联通知");
        addSBDXTv.setVisibility(View.VISIBLE);
        addSBDXTv.setOnClickListener(this);
        if (pageType == 0 || pageType == 2) {
            addSBDXTv.setEnabled(true);
        } else {
            addSBDXTv.setEnabled(false);
        }

//        filterLayout2 = (LinearLayout) mMainView.findViewById(R.id.sub_header_filter_layout2);
//        filterLayout2.setVisibility(View.GONE);

//        groupDelTv = (TextView) mMainView.findViewById(R.id.group_del_tv);
//        groupDelTv.setVisibility(View.GONE);

//        searchBtn = (Button) mMainView.findViewById(R.id.search_btn);
//        searchBtn.setOnClickListener(this);
//        searchBtn.setVisibility(View.GONE);


        headDowntv = (TextView) mMainView.findViewById(R.id.notice_head_down_tv);
        headDowntv.setOnClickListener(this);
        headUpTv = (TextView) mMainView.findViewById(R.id.notice_head_up_tv);
        headUpTv.setVisibility(View.GONE);


//        searchEt = (EditText) mMainView.findViewById(R.id.search_edt);
//        searchEt.setHint("");
//        searchEt.setVisibility(View.GONE);

        mLoadMoreFooterView = (LoadMoreFooterView) mRecyclerView.getLoadMoreFooterView();

//        mRecyclerView.setOnLoadMoreListener(this);
//        mRecyclerView.setOnRefreshListener(this);
        mRecyclerView.setRefreshEnabled(false);
        mRecyclerView.setLoadMoreEnabled(false);


        refreshView(mType);
        mMainView.findViewById(R.id.back).setOnClickListener(this);
    }

    public void initData() {
        noticeUserList.clear();
        if (!TextUtils.isEmpty(noticeUuid)) {
            getRelevanceListRequest();

        }

    }



//    public void onRefresh() {
//
//        mLoadMoreFooterView.setStatus(LoadMoreFooterView.Status.GONE);
//        noticeUserList.clear();
//        mAdapter.notifyDataSetChanged();
//
//    }


    public void getRelevanceListRequest() {
        String authtoken = SharedPreferencesUtils.getSharedPreferences(
                Constants.CONFIG_AUTHTOKEN, getContext());
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("Authorization", authtoken);
        params.put("uuid", noticeUuid);


        mRelevanceNoticeListPresenter.getRelevanceNoticeList(params);
    }






    private void refreshView(int type) {

        mAdapter = new RelevanceNoticeMainAdapter(getActivity(), type, noticeUserList, itemclick);
//        mListHeaderLayout.setVisibility(View.VISIBLE);
        mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        mRecyclerView.setIAdapter(mAdapter);
    }

    private View.OnClickListener itemclick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (ClickTimeSpanUtil.isFastDoubleClick()) {
                return;
            }


            final int i = v.getId();
            if (i == R.id.close_img) {
                final int currentOptIndex = Integer.parseInt(String.valueOf(v.getTag()));
                final TipsDialog deleteDialog = new TipsDialog(getContext());
                deleteDialog.setTitleMsg("删除确认");
                deleteDialog.setMsgHint("确定要删除这条关联通知吗？");
                deleteDialog.setCancelListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        deleteDialog.dismiss();
                    }
                });
                deleteDialog.setComfirmListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        deleteDialog.dismiss();
                        getChooseRelevanceList(currentOptIndex);
                    }
                });

                deleteDialog.show();



            }

        }
    };


    public void getChooseRelevanceList(int pos){
        ArrayList<NoticeInfoList> tempNoticeInfoList = new ArrayList<NoticeInfoList>();
        for( int i=0;i<noticeUserList.size();i++)
        {
            if(i != pos){
                tempNoticeInfoList.add(noticeUserList.get(i));
            }
        }

        if(tempNoticeInfoList.size() >0)
        {
            StringBuffer sb = new StringBuffer();
            for(int i=0;i<tempNoticeInfoList.size();i++)
            {
                sb.append(tempNoticeInfoList.get(i).getUuid());
                if (i < tempNoticeInfoList.size() - 1) {
                    sb.append(",");
                }
            }
            addRelevance(sb.toString());

        }else
        {
            addRelevance("");
        }
    }

    //添加关联操作
    private void addRelevance(String targetUuid)
    {
        String authtoken = SharedPreferencesUtils.getSharedPreferences(
                Constants.CONFIG_AUTHTOKEN, getContext());
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("Authorization", authtoken);
        params.put("uuid", noticeUuid);
        params.put("targetUuid", targetUuid);
        mAddRelevanceNoticePresenter.addRelevanceNotice(params);
    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode != Activity.RESULT_OK){
            return;
        }else{
            //刷新
            initData();

        }

    }
    @Override
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.group_add_tv) {
            if (noticeUuid == null) {
                noticeUuid = "0";
            }


            AddSearchRelevanceFragment atf = new AddSearchRelevanceFragment();
            Bundle bundle = new Bundle();
            bundle.putSerializable("notice", mNoticeInfoList);
            ArrayList<String> uuidList = new ArrayList<String>();

            if(noticeUserList.size() >0)
            {
                for(int j = 0;j < noticeUserList.size();j++)
                {
                    uuidList.add(noticeUserList.get(j).getUuid());
                }
                bundle.putStringArrayList("uuidList",uuidList);
            }
            atf.setArguments(bundle);
            atf.setTargetFragment(AddRelevanceNoticeFragment.this, 0);
            getFragmentManager().beginTransaction().add(R.id.reight_fl, atf, "addTriggerConditionFragment").addToBackStack("addTriggerConditionFragment").commit();

        } else if (i == R.id.notice_head_down_tv) {
            if (null != noticeUserList && noticeUserList.size() > 0) {

                if (pageType == 0) {
                    AddTriggerRelevanceFragment aif = new AddTriggerRelevanceFragment();
                    Bundle bundle = new Bundle();
//                    if (pageType != 0) {
                        bundle.putSerializable("notice", mNoticeInfoList);
//                    } else {
//                        bundle.putString("noticeUuid", noticeUuid);
//                    }
                    bundle.putInt("pageType", pageType);
                    aif.setArguments(bundle);

                    getFragmentManager().beginTransaction().replace(R.id.reight_fl, aif, "mAddTriggerRelevanceFragment").addToBackStack(null).commit();
                }
//                else {
//                    if (!noticeUserList.isEmpty()) {
//                        AddRecognitionIntervalFragment aif = new AddRecognitionIntervalFragment();
//                        Bundle bundle = new Bundle();
//                        if (pageType != 0) {
//                            bundle.putSerializable("notice", mNoticeInfoList);
//                        } else {
//                            bundle.putString("noticeUuid", noticeUuid);
//                        }
//                        bundle.putInt("pageType", pageType);
//                        aif.setArguments(bundle);
//
//                        getFragmentManager().beginTransaction().replace(R.id.reight_fl, aif, "43").addToBackStack(null).commit();
//                    } else {
//                        Toast.makeText(getContext(), "请先添加识别对象", Toast.LENGTH_SHORT).show();
//                    }
//                }

            } else {
                Toast.makeText(getContext(), "请先添加关联通知", Toast.LENGTH_SHORT).show();
            }


        } else if (i == R.id.botton_rl) {
            SharedPreferencesUtils.setBooleanSharedPreferences(
                    "noticeguide", true, getActivity());

            guideRl.setVisibility(View.GONE);
            dataRl.setVisibility(View.VISIBLE);


        } else if (i == R.id.back) {
            getFragmentManager().popBackStack();

        }

    }

    private MyNoticeListener myListener = new MyNoticeListener() {
        @Override
        public void refreshData(final String text) {

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {

//                    mAddNoticeUserDialog.dismiss();
                    //设置通知Id
                    noticeUuid = text;

                    noticeUserList.clear();
                    mAdapter.notifyDataSetChanged();
                    if (!TextUtils.isEmpty(text)) {
                        getRelevanceListRequest();
                    }


                }
            });

        }

        @Override
        public void refreshCancelData(final String text) {


        }

        @Override
        public void onResponse(List<Object> data) {

        }

    };


    @Override
    public void onRelevanceNoticeListSuccess(Object obj) {
        ArrayList<NoticeInfoList> list = (ArrayList<NoticeInfoList>) obj;
        if (null != list && list.size() > 0) {
            noticeUserList.addAll(list);
        }
        if (null != getActivity()) {
            mAdapter.notifyDataSetChanged();
            mLoadMoreFooterView.setStatus(LoadMoreFooterView.Status.GONE);
        }
    }

    @Override
    public void onRelevanceNoticeListFailed(Object object) {

    }

    @Override
    public void setPresenter(BasePresenter tp) {

    }

    @Override
    public void addRelevanceNoticeSuccess(Object data) {
        initData();
    }

    @Override
    public void addRelevanceNoticeFailed(Object object) {

    }
}








